package com.pc.admin.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @Author : ZJ
 * @create 2023/3/23 13:09
 */

@Slf4j
public class DaDatest {

//
//    public static void main(String[] args) {
//
//        List<Object[]> data = new ArrayList<>();
//// add data to the list
//
//        String[] headers = {"Header 1", "Header 2", "Header 3"};
//
//
//        exportToExcel(data, headers, "D:\\excel\\myFile.xlsx");
//
//    }



    public static  <T> void exportToExcel( List<String> data, List<String> headers, String fileName, List<T> list) {

        //数据拼装
        List<Map<String, Object>> list1 = new ArrayList<>();
        for (Object obj : list) {
            Map<String, Object> hashMap = new LinkedHashMap<>(10);
            for (String fieldName : data) {
                try {
                    String firstLetter = fieldName.substring(0,1).toUpperCase();
                    String getter = "get" + firstLetter + fieldName.substring(1);
                    Method method = obj.getClass().getMethod(getter, new Class[]{});
                    Object value = method.invoke(obj, new Object[]{});
                    if (value == null) {
                        hashMap.put(fieldName, "");
                    } else {
                        hashMap.put(fieldName, value);
                    }
                } catch (Exception e) {
                    log.error("该对象没有对应的列");
                }
            }
            list1.add(hashMap);
        }


        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers.get(i));
        }
        int rowNum = 1;
        for (String rowData : data) {
            Row row = sheet.createRow(rowNum++);
            for (int i = 0; i < rowData.length(); i++) {
                 row.createCell(i);
            }
        }
        try {
            FileOutputStream outputStream = new FileOutputStream(fileName);
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
